﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS运单_新增关务集装箱信息
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMStoGWAddContainerInfoController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public TMStoGWAddContainerInfoController(ILogger<TMStoGWAddContainerInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            //_logger = loggerFactory.CreateLogger<TMStoGWAddContainerInfoController>();
        }

        /// <summary>
        /// TMS运单_新增关务集装箱信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSAddContainer([FromBody] TMStoGWAddContainerInfoRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMStoCRMWayBillInfoResponseDto re = new TMStoCRMWayBillInfoResponseDto();
            CRM_CreateFyInfoRequestDto strRequest = new CRM_CreateFyInfoRequestDto();
            string times = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();

            GW_AddContainerInfoRequestDto input = new GW_AddContainerInfoRequestDto();
            List<GW_AddContainerInfo_Data_Dto> input_data = new List<GW_AddContainerInfo_Data_Dto>();
            GW_AddContainerInfo_IfInfo_Dto input_info = new GW_AddContainerInfo_IfInfo_Dto();
            if (strparm.waybill_no=="")
            {
                strMsg = "物流发运单不能为空，调用失败！";
            }


            try
            {


                if (strMsg=="")
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add("waybill_no", strparm.waybill_no);
                    DataTable m_dt = MethodHelp.GetTableInfo("TMS0130", dic,con);
                    if (m_dt.Rows.Count>0)
                    {
                        foreach (DataRow item in m_dt.Rows)
                        {

                            List<GW_AddContainerInfo_DataDetailes_Dto> inp_de = new List<GW_AddContainerInfo_DataDetailes_Dto>();

                            dic = new Dictionary<string, string>();
                            dic.Add("deliverno", item["deliverno"].ToString());
                            DataTable d_dt = MethodHelp.GetTableInfo("TMS0129", dic, con);
                            if (d_dt.Rows.Count>0)
                            {
                                int i = 1;
                                foreach (DataRow row in d_dt.Rows)
                                {
                                    string NOTE4 = "";

                                    if (row["transport_type"].ToString()=="4")
                                    {
                                        NOTE4 = row["six_link"].ToString();
                                    }else if (row["transport_type"].ToString() == "5")
                                    {
                                        NOTE4 = row["flight_no"].ToString();
                                    }
                                    else
                                    {

                                    }

                                    inp_de.Add(new GW_AddContainerInfo_DataDetailes_Dto
                                    {
                                        LINENUM = i,
                                        CONTAINERNO = row["cabinet_number"].ToString(),
                                        NOTE4= NOTE4,
                                        LOADQTY = DB.ToDouble(row["ship_qty"].ToString()),
                                        ERPGNO= row["material_code"].ToString()

                                    });

                                    i++;
                                }

                                if (inp_de.Count > 0)
                                {
                                    input_data.Add(new GW_AddContainerInfo_Data_Dto
                                    {
                                        COPID = d_dt.Rows[0]["factory_code"].ToString(),
                                        LISTBILLNO = d_dt.Rows[0]["deliverno"].ToString(),
                                        BATCHNO = d_dt.Rows[0]["six_link"].ToString(),
                                        TRAFCODE = d_dt.Rows[0]["transport_type"].ToString(),
                                        VOYNO = d_dt.Rows[0]["flight_no"].ToString(),
                                        DETAILED = inp_de
                                    });

                                }
                            }
                           
                        }

                        if (input_data.Count > 0)
                        {
                            input_info.MSGID = times;
                            input_info.IFID = "CUCIN";
                            input_info.RECEIVER = "GH";
                            input_info.ASYN = "0";
                            input_info.SENDER = "TMS";

                            input.IFINFO = input_info;
                            input.DATA = input_data;

                            if (input != null)
                            {
                                Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                                urldic.Add("function_description", "内部: 关务装柜清单柜号信息更新");//查看URL配置表地址描述
                                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                if (url_dt.Rows.Count > 0)
                                {
                                    string jsonText = JsonConvert.SerializeObject(input);
                                    var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                    GW_AddContainerInfoResponseDto psp = JsonConvert.DeserializeObject<GW_AddContainerInfoResponseDto>(reAgv);
                                    if (psp.code >0)
                                    {
                                        strMsg = psp.message;
                                    }
                                }
                            }
                        }
                        else
                        {
                            strMsg = "运单<" + strparm.waybill_no + ">明细信息！";
                        }
                    }



                   
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            //_logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
